package com.baihang.platform.shiro;

import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.baihang.platform.model.UserModel;
import com.google.common.collect.Sets;

public class SystemAuthorizingRealm extends AuthorizingRealm {
	
	private SystemAuthorizingService service;
	
	public SystemAuthorizingService getService() {
		return service;
	}

	public void setService(SystemAuthorizingService service) {
		this.service = service;
	}

	/**
	 * 权限认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		User user = (User) arg0.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		UserModel model = service.getUserModel(user.getUserName());
		if(model ==null) {
			SecurityUtils.getSubject().logout();
			return null;
		}
		// 设置角色
		List<String> roleCodeList = service.getRoleCodeList(user.getUserCode());
		Set<String> roleCodeSet = Sets.newHashSet(roleCodeList.iterator());
		info.setRoles(roleCodeSet); 
				
		// 设置权限
		List<String> roleAuthzList = service.getRoleAuthzList(user.getUserCode());
		Set<String> authzCodeSet = Sets.newHashSet(roleAuthzList.iterator());
		info.setStringPermissions(authzCodeSet);
		return info;
	}

	/**
	 * 身份认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken userToken = (UsernamePasswordToken)token;
		String userName = userToken.getUsername();
		String password = String.valueOf(userToken.getPassword());
		UserModel model = service.getUserModel(userName,password);
		if(model !=null) {
			User user = new User();
			user.setUserName(model.getUserName());
			user.setRealName(model.getChineseName());
			user.setUserCode(model.getUserCode());
			user.setGroupCode(model.getGroupCode());
			//SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, model.getPassword(), userName);
			return info;
		}
		return null;
	}

	

}
